import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter);

const routes = [

	{
		path: '/login',
		name: 'login',
		component: () => import('../views/LoginView.vue'),
		meta: {
			requiresAuth: false
		} // 不需要身份验证
	},
	{
		path: '/register',
		component: () => import('../views/register.vue'),
		meta: {
			requiresAuth: false
		} // 不需要身份验证
	},
	{
		path: '/',
		name: 'main',
		component: () => import('../views/main.vue'),
		meta: {
			requiresAuth: true
		}, // 需要身份验证
		children: [{
				path: '/home',
				name: 'home',
				component: () => import('../views/home.vue'),
				meta: {
					requiresAuth: true
				} // 需要身份验证
			},
			{
				path: '/user',
				name: 'user',
				component: () => import('../views/user/user.vue'),
				meta: {
					requiresAuth: true
				}
			},
			{
				path: '/announce',
				name: 'announce',
				component: () => import('../views/announce/announce.vue'),
				meta: {
					requiresAuth: true
				}
			},
			{
				path: '/category',
				name: 'category',
				component: () => import('../views/category/category.vue'),
				meta: {
					requiresAuth: true
				}
			},
			{
				path: '/course',
				name: 'course',
				component: () => import('../views/course/course.vue'),
				meta: {
					requiresAuth: true
				}
			},
			{
				path: '/order',
				name: 'order',
				component: () => import('../views/order/order.vue'),
				meta: {
					requiresAuth: true
				}
			},
			{
				path: '/permission',
				name: 'permission',
				component: () => import('../views/permission/permission.vue'),
				meta: {
					requiresAuth: true
				}
			},
            {
				path: '/permission_role',
				name: 'permission_role',
				component: () => import('../views/permission/rolepermission.vue'),
				meta: {
					requiresAuth: true
				}
			},
			{
				path: '/plan',
				name: 'plan',
				component: () => import('../views/plan/plan.vue'),
				meta: {
					requiresAuth: true
				}
			},
			{
				path: '/product',
				name: 'product',
				component: () => import('../views/product/product.vue'),
				meta: {
					requiresAuth: true
				}
			},
			{
				path: '/role',
				name: 'role',
				component: () => import('../views/role/role.vue'),
				meta: {
					requiresAuth: true
				}
			}
		]
	},


];

const router = new VueRouter({
	mode: 'history',
	base: process.env.BASE_URL,
	routes
});

router.beforeEach((to, from, next) => {
	const requiresAuth = to.meta.requiresAuth; // 获取路由配置中的 requiresAuth 字段

	// 判断用户是否已登录，存储在localStorage 中的登录状态
	const isLoggedIn = localStorage.getItem("token") != null;

	if (requiresAuth && !isLoggedIn) {
		// 如果请求路径需要身份验证且用户未登录，则重定向到登录页面
		next('/login');
	} else {
		// 否则，允许用户继续访问
		next();
	}
});

//解决Avoided redundant navigation to current location报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
	return originalPush.call(this, location).catch(err => err)
};

export default router;